package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class CookieTestServlet
 */
@WebServlet("/CookieTestServlet")
public class CookieTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieTestServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		for(int i = 0 ; i < 3; ++i){
			Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i);
			response.addCookie(cookie);
			//
			cookie = new Cookie("Persistent-Cookie-" + i , "Cookie-Value-P" +i);
			cookie.setMaxAge(60);
			response.addCookie(cookie);
		}
		
		//
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//
		String title = "Active Cookies";
		out.println(Constants.docType + ServletUtilities.headWithTitle(title) + 
				"<body>\n<h1>" + title + "</h1>\n<table border=1>\n" +
				"<tr>\n<th>CookieName</th><th>Cookie Value</th></tr>"
				);
		//
		Cookie[] cookies = request.getCookies();
		if(null == cookies){
			out.println("<tr><th colspan=2>No Cookies</th></tr>");
		}else{
			for(Cookie cookie : cookies){
				out.println("<tr><td>" + cookie.getName() + "</td><td>" + cookie.getValue() + "</td></tr>");
			}
		}
		//
		out.println("</table></body></html>");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private static final Logger logger = 
			Logger.getLogger(CookieTestServlet.class);

}
